package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查出所有分类,组装成树形结构
        List<CategoryEntity> entityList = baseMapper.selectList(null);
        //找到所有的一级分类
        List<CategoryEntity> level1Menu = entityList.stream().
                filter(categoryEntity -> categoryEntity.getParentCid() == 0
                ).map((menu) -> {
            menu.setChildren(getChildren(menu, entityList));
            return menu;
        }).sorted((menu1, menu2) -> (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()))
                .collect(Collectors.toList());

        return level1Menu;

    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查当前菜单是否被引用
        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        //比如2号下面有34号,34号下面有225号 [2, 34, 225]
        List<Long> parentPath = findParentPath(catelogId, paths);
        //将225 25 2逆序
        Collections.reverse(parentPath);
        return (Long[]) parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     *
     * @param category
     */


   // @CacheEvict(value={"catalogry"},key="'getLevel1Category'") //失效模式

    //@Caching(evict = {
    //        @CacheEvict(value={"catalogry"},key="'getLevel1Category'"),
    //        @CacheEvict(value={"catalogry"},key="'getCatalogJson'")
    //})
    @Transactional
    @Override
    //value指定缓存分区删除该分区下的所有key
    @CacheEvict(value="catalogry",allEntries = true)
    //@CachePut双写模式必须要把修改后的结果返回才能写入redis中
    //缓冲穿透 查询一个null将大量请求放入数据 解决方法 缓冲空数据
    //缓存击穿,大量请求同时查询一个正好过期的数据 解决方案: 加锁
    //缓存雪崩,大量的key同时过期,解决:加上过期时间
    //写模式
    /**
     *缓存与数据库一致性
     * 读写锁
     * 引入cancel感知到mysql去更新数据库
     * 读多写多,直接查询数据库
     */
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        if (StringUtils.isNotEmpty(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }
        //同时修改缓存
        //删除缓存等待下次主动查询
    }
    //每一个需要缓存中,我们都要指定方法哪个名字的缓存,相当于缓存分区
    @Cacheable(value={"catalogry"},key = "#root.method.name") //代表当前方法的结果需要缓存,如果缓存中有方法不用调用,如果缓存中没有调用方法,最后将结果放入缓存中
    //因为key是spirngel表达式所以用字符串必须用" '' "
    @Override
    //自定义指定生成的key  指定生成的存活的时间 将保存的数据变为json数据
    public List<CategoryEntity> getLevel1Category() {
        System.out.println("getLevel1Category方法调用");
        List<CategoryEntity> list = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return list;
    }

    @Override
    @Cacheable(value={"catalogry"},key = "#root.method.name")
    public Map<String, List<Catelog2Vo>> getCatalogJson(){
           return getCatalogJsonFromDBRedissonLock();
    }
    /**
     * 使用自定义缓存
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJson2() {
        //加入缓存redis 缓存中存的json字符串
        //json跨语言跨平台
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            System.out.println("缓存不命中查询数据库");
            //缓存中没有数据,将对象转为json
            Map<String, List<Catelog2Vo>> catalogJsonFromDB = getCatalogJsonFromDBRedissonLock();
            stringRedisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(catalogJsonFromDB), 1, TimeUnit.DAYS);
            return catalogJsonFromDB;
        }
        System.out.println("缓存命中");
        Map<String, List<Catelog2Vo>> list = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return list;
    }

    /**
     * 缓存里吗的数据和数据库保持一致性
     * 1.双写模式
     * 2.失效模式
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDBRedissonLock() {
        //分布式锁去redis占位
        //锁的名称 锁的粒度,越细越快
        RLock lock = redisson.getLock("catalogJson-lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> dataFromDB;
        try {
            dataFromDB = getDataFromDB();
        } finally {
               lock.unlock();
        }
        return dataFromDB;


    }
    //从数据库查询并封装

    /**
     * 1.空结果返回,解决缓存穿透问题
     * 2.设置过期时间(加随机值):解决缓存雪崩问题
     * 3.加锁,解决缓存击穿问题
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDBRedisLocal() {
        //分布式锁去redis占位
        String uuid = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            System.out.println("获取分布式锁成功");
            //加锁成功
            //设置过期时间 必须和加锁是同步的因此不能之后设置,在占锁的同时设置过期时间stringRedisTemplate.expire("lock",30,TimeUnit.SECONDS);
            Map<String, List<Catelog2Vo>> dataFromDB;
            try {
                dataFromDB = getDataFromDB();
            } finally {
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('get',KEYS[1]) else return 0 end";
                //删除锁
                stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);

            }
            //解锁 删除锁和解锁=原子操作利用 Lua脚本
            //if(uuid.equals(stringRedisTemplate.opsForValue().get("lock"))){
            //    stringRedisTemplate.delete("lock");//删除锁
            //
            //}
            return dataFromDB;

        } else {
            //加锁失败...重试   自旋
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("获取分布式锁失败重试");
            return getCatalogJsonFromDBRedisLocal();
        }
    }

    private Map<String, List<Catelog2Vo>> getDataFromDB() {
        //得到锁中应该再去缓存中再确定一次
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<Catelog2Vo>> list = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return list;
        }
        System.out.println("查询了数据库.......");
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //查出所有一级分类
        List<CategoryEntity> level1Category = getParent_cid(selectList, 0L);
        Map<String, List<Catelog2Vo>> parent_id = level1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查出一级分类中的二级分类
            List<CategoryEntity> entities = getParent_cid(selectList, v.getCatId());
            List<Catelog2Vo> list = null;
            if (entities != null) {
                list = entities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找当前二级分类找三级分类封装成vo
                    List<CategoryEntity> levl3CatalogList = getParent_cid(selectList, l2.getCatId());
                    if (levl3CatalogList != null || levl3CatalogList.size() > 0) {
                        //封装成指定格式
                        List<Catelog2Vo.Catelog3Vo> level3List = levl3CatalogList.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(level3List);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return list;
        }));
        //应该是放入缓存之后才能释放锁
        stringRedisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(parent_id), 1, TimeUnit.DAYS);
        return parent_id;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDB() {
        /**
         * 將数据库的多次查询变为一次
         */
        //只要是同一把锁就能锁住这个锁的所有的线程
        // synchronized (this){} springboot的所有组件都是单例的
        //TODO 本地锁,只能锁当前进程,在分布式场景想要锁住所有必须使用分布式锁
        synchronized (this) {
            //得到锁中应该再去缓存中再确定一次
            return getDataFromDB();

        }
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parentCid) {
        //return this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parentCid).collect(Collectors.toList());
        return collect;
    }

    //递归查找收集 225,34,2
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 获取所有子菜单
     *
     * @param root
     * @param all  从哪里获取子菜单
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(category -> category.getParentCid() == root.getCatId())
                .map(categoryEntity -> {
                            categoryEntity.setChildren(getChildren(categoryEntity, all));
                            return categoryEntity;
                        }
                )
                .sorted((menu1, menu2) -> (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()))
                .collect(Collectors.toList());
        return children;
    }

}